<template>
  <div class="fund-detail">
    <el-card shadow="never">
      <div class="header-container">
        <el-page-header @back="goBack" content="客户资金详情">
        </el-page-header>
        <el-button-group>
          <el-tooltip effect="dark" content="审核" placement="top" v-role="['/customer/fund:audit']">
            <el-button type="primary" v-if="fundDetail.tradeStatus =='AUDITING'" icon="el-icon-s-check"
                       @click="audit()">审核
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="回款\回料审核初审通过" placement="top" v-role="['/customer/fund:audit']">
            <el-button v-if="fundDetail.tradeStatus == 'INIT'" type="primary"
                       @click="auditEncash(fundDetail.id,true)">回款\回料初审通过
            </el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="回款\回料拒绝" placement="top" v-role="['/customer/fund:audit']"
                      v-if="fundDetail.tradeType=='ENCASH'">
            <el-button v-if="fundDetail.tradeStatus == 'INIT'" type="warning"
                       @click="auditEncash(fundDetail.id,false)">回款拒绝
            </el-button>
          </el-tooltip>
        </el-button-group>
      </div>

      <div v-loading="loading" element-loading-text="数据正在加载中">
        <el-form :model="fundDetail" label-width="120px" disabled>
          <!-- 基本信息 -->
          <el-divider content-position="left">交易基本信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="客户姓名：">
                <span class="detail-value">{{ fundDetail.cusName || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交易类型：">
                <el-tag :type="getTradeTypeTagType(fundDetail.tradeType)">
                  {{ tradeTypeMap[fundDetail.tradeType] || '--' }}
                </el-tag>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交易状态：">
                <el-tag :type="getStatusTagType(fundDetail.tradeStatus)">
                  {{ tradeStatusMap[fundDetail.tradeStatus] || '--' }}
                </el-tag>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="交易金额：">
                <span class="detail-value amount">¥{{ formatNumber(fundDetail.amount) || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="数量/重量：">
                <span class="detail-value">{{ formatWeight(fundDetail.weight) || '--' }}g</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交易单价：">
                <span class="detail-value">¥{{ formatNumber(fundDetail.price) || '--' }}/g</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="物料类型：">
                <span class="detail-value">{{ materialTypeMap[fundDetail.materialType] || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交易时间：">
                <span class="detail-value">{{ fundDetail.tradeTime || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="交易余额：">
                                <span class="detail-value balance">¥{{
                                    formatNumber(fundDetail.balance) || '--'
                                  }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 银行信息 -->
          <el-divider content-position="left">银行账户信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="银行名称：">
                <span class="detail-value">{{ fundDetail.bankName || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="开户支行：">
                <span class="detail-value">{{ fundDetail.bankBranchName || '--' }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="账户名：">
                <span class="detail-value">{{ fundDetail.accName || '--' }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="银行卡号：">
                <span class="detail-value">{{ fundDetail.bankCardNo || '--' }}</span>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 附件资料 -->
          <el-divider content-position="left">附件资料</el-divider>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="附件资料：">
                <div v-if="fundDetail.accessoryGroup && fundDetail.accessoryGroup.length > 0"
                     class="accessory-list">
                  <div v-for="(item, index) in fundDetail.accessoryGroup" :key="index"
                       class="accessory-item">
                    <el-image :src="getImageUrl(item.filePath)"
                              :preview-src-list="getImageUrlList()" fit="cover" class="accessory-image"
                              @click="previewImage(index)">
                    </el-image>
                  </div>
                </div>
                <span v-else class="no-data">暂无附件资料</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>
    <!-- 审核 -->
    <el-dialog title="审核" :visible="auditDialogVisible" width="60%" @close="cancelAudit" :close-on-click-modal="false">
      <el-form :model="auditForm" :rules="auditRules" ref="auditFormRef" label-width="120px">
        <el-form-item label="审核状态：" prop="auditStatus">
          <el-radio-group v-model="auditForm.auditStatus" @change="onAuditStatusChange">
            <el-radio label="AUDIT_PASS">审核通过</el-radio>
            <el-radio label="CANCEL">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核备注：" prop="auditRemark" :required="auditForm.auditStatus === 'CANCEL'"
                      v-if="auditForm.ext">
          <el-input v-model="auditForm.auditRemark" type="textarea" placeholder="请输入审核备注" :rows="3"
                    class="w-100"></el-input>
        </el-form-item>
        <el-form-item label="实时单价：" prop="tradeTime"
                      v-if="fundDetail.tradeType=='SAVE' || fundDetail.tradeType=='TAKE'">
          <span style="color: #e6a23c">{{ tradeRealTimePrice }}</span>
        </el-form-item>

        <el-form-item label="交易单价(元)：" prop="price"
                      v-if="fundDetail.tradeType=='SAVE' ">
          <el-input v-model="auditForm.price" placeholder="请输入交易单价" maxlength="7"
                    style="width: 160px"></el-input>
        </el-form-item>
        <el-form-item label="交易重量(g)：" prop="weight"
                      v-if="fundDetail.tradeType=='SAVE' ">
          <el-input v-model="auditForm.weight" placeholder="请输入交易重量" style="width: 160px"
                    maxlength="5"></el-input>
        </el-form-item>
        <el-form-item label="附件" prop="accessoryGroupId">
          <div class="multi-upload-container">
            <!-- 上传组件 -->
            <el-upload action="#" list-type="picture-card" :multiple="true" :file-list="fileList"
                       :before-upload="beforeUpload" :on-change="handleChange" :on-remove="handleRemove"
                       :auto-upload="false" :limit="9" :on-exceed="handleExceed" accept="image/*">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">
                请上传图片文件，单张图片不超过5MB
              </div>
            </el-upload>

            <!-- 上传按钮 -->
            <el-button type="primary" @click="submitUpload" :loading="uploading"
                       :disabled="fileList.length === 0">
              {{ uploading ? '上传中...' : '开始上传' }}
            </el-button>

            <!-- 结果展示 -->
            <div v-if="uploadedUrls.length > 0" class="result-container">
              <h4>上传成功：</h4>
              <div v-for="(url, index) in uploadedUrls" :key="index" class="image-item">
                <el-image :src="url" fit="cover"
                          style="width: 100px; height: 100px; margin-right: 10px;"></el-image>
                <div class="image-url">{{ url }}</div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAudit">取消</el-button>
        <el-button type="primary" @click="confirmAudit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {auditCustomerFund, encashPreAudit, getCustomerFundDetail} from '../api/customer'
import {IMG_URL} from '@/utils/utils'
import {createDirectClient} from '@/utils/oss'
import {uploadAccessory} from '@/api/login'
import moment from "moment";

export default {
  name: 'FundDetail',
  data() {
    return {
      fileList: [],
      loading: false,
      fundDetail: {},
      // 物料类型映射
      materialTypeMap: {
        'GOLD': '黄金',
        'SILVER': '白银',
        'PLATINUM': '铂金',
        'PALLADIUM': '钯金',
      },
      // 交易类型映射
      tradeTypeMap: {
        'RECHARGE': '入款',
        'ENCASH': '回款',
        'BUY': '买料',
        'SELL': '卖料',
        'SAVE': '入料',
        'TAKE': '回料',
        'REFUND': '违约结算',
        'ADD_RETAINER': '追加定金',
      },
      // 交易状态映射
      tradeStatusMap: {
        'INIT': '申请中',
        'AUDITING': '审核中',
        'AUDIT_PASS': '通过',
        'CANCEL': '不通过',
      },
      IMG_URL,
      uploadedUrls: [],
      uploading: false,
      auditDialogVisible: false,
      auditForm: {
        auditStatus: null,
        auditRemark: null,
        weight: '',
        price: ''
      },

      auditRules: {
        auditStatus: [{required: true, message: '请选择审核状态', trigger: 'change'}],
        auditRemark: [
          {
            validator: (rule, value, callback) => {
              if (this.auditForm.auditStatus === 'CANCEL' && (!value || !String(value).trim())) {
                callback(new Error('请选择不通过时，备注必填'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
      },
      statisticsData: {},
      tradeRealTimePrice: 0,
    }
  },
  mounted() {
    // 监听WebSocket消息事件
    this.$onWebSocket('statisticsUpdate', this.onMessageReceived);
  },
  created() {
    this.init()
  },
  methods: {
    updateStatisticsData(data) {
      // console.log("通知数据：", data);
      this.statisticsData = data;
      if (this.fundDetail) {
        if (this.fundDetail.tradeType === "SAVE") {
          this.tradeRealTimePrice = this.statisticsData.goldBuyPrice;
        } else if (this.fundDetail.tradeType === "TAKE") {
          this.tradeRealTimePrice = this.statisticsData.goldSellPrice;
        } else {
          this.tradeRealTimePrice = 0;
        }
      }
    },
    onMessageReceived(data) {
      this.updateStatisticsData(data.data)
    },
    // 初始化数据
    async init() {
      const id = this.$route.params.id || this.$route.query.id
      if (!id) {
        this.$message.error('缺少交易记录ID')
        this.goBack()
        return
      }

      this.loading = true
      try {
        const response = await getCustomerFundDetail(id)
        this.fundDetail = response || {}
      } catch (error) {
        this.fundDetail = {}
        console.error('获取资金详情失败:', error)
      } finally {
        this.loading = false
      }
    },

    // 返回上一页
    goBack() {
      this.$router.go(-1)
    },

    // 获取交易类型标签样式
    getTradeTypeTagType(tradeType) {
      const typeMap = {
        'RECHARGE': 'success',
        'ENCASH': 'warning',
        'BUY': 'primary',
        'SELL': 'danger',
        'SAVE': 'info',
        'TAKE': 'warning',
        'REFUND': 'danger',
        'ADD_RETAINER': 'success'
      }
      return typeMap[tradeType] || 'info'
    },

    // 获取状态标签样式
    getStatusTagType(status) {
      const statusMap = {
        'INIT': 'primary',
        'AUDITING': 'warning',
        'AUDIT_PASS': 'success',
        'CANCEL': 'danger'
      }
      return statusMap[status] || 'info'
    },

    // 格式化数字
    formatNumber(num) {
      if (num === null || num === undefined || num === '') return '--'
      return Number(num).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    },

    // 获取图片URL
    getImageUrl(filePath) {
      if (!filePath) return ''
      return this.IMG_URL + filePath
    },

    // 获取图片预览列表
    getImageUrlList() {
      if (!this.fundDetail.accessoryGroup || this.fundDetail.accessoryGroup.length === 0) {
        return []
      }
      return this.fundDetail.accessoryGroup.map(item => this.getImageUrl(item.filePath))
    },

    // 预览图片
    previewImage(index) {
      // 这里可以添加自定义的图片预览逻辑
    },

    // 格式化文件大小
    formatFileSize(size) {
      if (!size) return '--'
      const units = ['B', 'KB', 'MB', 'GB']
      let index = 0
      let fileSize = size
      while (fileSize >= 1024 && index < units.length - 1) {
        fileSize /= 1024
        index++
      }
      return fileSize.toFixed(2) + ' ' + units[index]
    },
    // 重量 千分符
    formatWeight(weight) {
      if (weight === null || weight === undefined || weight === '') return '0'
      const num = Number(weight)
      if (!isFinite(num)) return '0'
      return num.toLocaleString('zh-CN')
    },

    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      this.fileList = fileList
    },

    // 移除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
    },

    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${fileList.length} 张图片`)
    },

    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt5M) {
        this.$message.error('单张图片大小不能超过5MB!')
      }

      return isImage && isLt5M
    },

    // 提交上传
    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择图片')
        return
      }
      this.uploading = true
      this.uploadedUrls = []

      try {
        const client = createDirectClient()
        console.log(this.fileList, '提交上传fileList');

        const uploadPromises = this.fileList.map(file => {
          let fileSuffix = `.${file.name.split('.')[1]}`
          let prefix = process.env.VUE_APP_CERT_SAVE_PREFIX + moment(new Date()).format("yyyyMMDD") + "/" + moment(new Date()).format("yyyyMMDDHHmmssSSS") + fileSuffix;
          client.multipartUpload(prefix, file.raw).then(res => {
            let params = {
              dataClassify: 'other',
              groupId: this.auditForm.accessoryGroupId || '',
              filePath: res.name,
              storageMethod: 'oss'
            }
            uploadAccessory(params).then(res => {
              this.$message.success('附件上传成功!')
              this.auditForm.accessoryGroupId = res
            }).catch(error => {
              console.error('附件上传失败:', error)
            })
          }).catch(error => {
            console.error('OSS上传失败:', error)
          })
        })
      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('上传失败，请重试')
      } finally {
        this.uploading = false
      }
    },
    // 审核
    audit() {
      this.auditDialogVisible = true;
      this.auditForm.id = this.fundDetail.id;
      this.auditForm.auditStatus = this.fundDetail.tradeStatus;
      this.auditForm.price = this.fundDetail.price;
      this.auditForm.weight = this.fundDetail.weight;
    },
    // 确认审核
    confirmAudit() {
      console.log("确认审核");
      this.$refs.auditFormRef.validate((valid) => {
        if (!valid) {
          return false;
        }
        let params = {
          id: this.auditForm.id,
          tradeStatus: this.auditForm.auditStatus,
          remarks: this.auditForm.auditRemark,
          tradeTime: this.auditForm.tradeTime,
          accessoryGroupId: this.auditForm.accessoryGroupId,
          price: this.auditForm.price,
          weight: this.auditForm.weight,
        }
        auditCustomerFund(params).then(res => {
          this.$message.success('审核成功');
          this.cancelAudit();
          this.init();
        }).catch(() => {
          this.$message.error('审核失败');
        });
      });
    },
    // 审核状态切换
    onAuditStatusChange() {
      // 状态变为通过时，清空并清除备注校验提示；为不通过时，触发校验
      if (this.auditForm.auditStatus === 'AUDIT_PASS') {
        this.auditForm.auditRemark = this.auditForm.auditRemark || '';
        this.$nextTick(() => this.$refs.auditFormRef.clearValidate('auditRemark'));
      } else if (this.auditForm.auditStatus === 'CANCEL') {
        this.$nextTick(() => this.$refs.auditFormRef.validateField('auditRemark'));
      }
    },
    // 取消审核
    cancelAudit() {
      this.fileList = [];
      this.uploadedUrls = [];
      this.uploading = false;
      this.auditDialogVisible = false;
      this.$refs.auditFormRef.clearValidate();
      // 如果需要重置字段值，可以调用resetFields，但注意这会重置所有字段到初始值
      this.$refs.auditFormRef.resetFields();
    },
    auditEncash(id, isPass) {
      let title = isPass ? '是否确认初审通过？' : '是否确认初审拒绝？';
      this.$confirm(title, '初审提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {

        let params = {
          id: id,
          tradeStatus: isPass ? 'AUDITING' : 'CANCEL'
        }
        encashPreAudit(params).then(res => {
          this.$message.success('审核成功');
          this.init();
        }).catch(() => {
          this.$message.error('审核失败');
        });
      }).catch(() => {
        this.$message.info('已取消操作');
      });
    },
  }
}
</script>

<style lang="scss" scoped>
.header-container {
  display: flex;
  align-items: center; /* 垂直居中 */
}

.header-container .el-button-group {
  margin-left: 30px; /* 按钮与 page-header 的间距 */
}

.fund-detail {
  .detail-value {
    font-size: 14px;
    color: #333;
    font-weight: 500;

    &.amount {
      color: #E6A23C;
      font-size: 16px;
      font-weight: bold;
    }

    &.balance {
      color: #67C23A;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .info-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    padding: 8px 0;

    .info-label {
      font-size: 14px;
      color: #606266;
      margin-right: 12px;
      min-width: 80px;
      font-weight: 500;
    }
  }

  .accessory-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
    margin-top: 8px;

    .accessory-item {
      display: flex;
      align-items: center;
      padding: 12px;
      border: 1px solid #EBEEF5;
      border-radius: 6px;
      background: #FAFAFA;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #409EFF;
        background: #F0F9FF;
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
      }

      .accessory-image {
        width: 60px;
        height: 60px;
        border-radius: 4px;
        border: 1px solid #EBEEF5;
      }

      .accessory-info {
        flex: 1;

        .accessory-name {
          font-size: 14px;
          color: #333;
          margin-bottom: 4px;
          max-width: 120px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          font-weight: 500;
        }

        .accessory-size {
          font-size: 12px;
          color: #999;
        }
      }
    }
  }

  .no-data {
    color: #999;
    margin-left: 8px;
  }

  .action-buttons {
    text-align: center;
    margin-top: 30px;
    padding: 20px 0;
    border-top: 1px solid #EBEEF5;
  }

  .el-divider {
    margin: 30px 0 20px 0;

    ::v-deep .el-divider__text {
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }
  }


  .el-tag {
    font-weight: 500;
    font-size: 13px;
  }

  // 响应式布局
  @media (max-width: 768px) {
    .el-col {
      margin-bottom: 10px;
    }

    .info-item {
      flex-direction: column;
      align-items: flex-start;

      .info-label {
        margin-bottom: 5px;
        margin-right: 0;
      }
    }

    .accessory-item {
      min-width: 100%;
    }
  }
}
</style>
